<template>
  <div class="meal-order-card" @click="handleClick">
    <div class="header">
      <span>订单号：{{ order.orderNumber }}</span>
      <span class="status">{{ order.status }}</span>
    </div>
    <div class="info">
      <span>下单时间：{{ order.createTime ? order.createTime.replace('T', ' ') : '' }}</span>
      <span>座位号：{{ order.seatNumber }}</span>
    </div>
    <div class="footer">
      <span
        >总金额：<b>￥{{ order.totalAmount }}</b></span
      >
    </div>
    <!-- 订单详情部分 -->
    <div v-if="showDetails && orderDetails.length > 0" class="details">
      <div v-for="item in orderDetails" :key="item.itemId" class="item">
        <span>{{ item.mealName }}（{{ item.mealType }}）x{{ item.quantity }}</span>
        <span>￥{{ item.price }} × {{ item.quantity }} = ￥{{ item.subtotal }}</span>
      </div>
    </div>
    <div v-else-if="showDetails && !orderDetails.length" class="details">
      <p class="no-details">暂无订单详情</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import api from '@/utils/api'

interface OrderItem {
  itemId: number
  mealName: string
  mealType: string
  price: number
  quantity: number
  subtotal: number
}

const props = defineProps<{
  order: {
    orderId: number
    orderNumber: string
    status: string
    createTime: string
    seatNumber: string
    totalAmount: number
  }
}>()

const showDetails = ref(false)
const orderDetails = ref<OrderItem[]>([])
const loading = ref(false)
const error = ref<string | null>(null)

const handleClick = async () => {
  if (!showDetails.value) {
    loading.value = true
    error.value = null
    try {
      const res = await api.get(`/api/orders/train-meals/${props.order.orderId}/details`)
      if (res.data && res.data.orderItems) {
        orderDetails.value = res.data.orderItems
      } else {
        orderDetails.value = []
      }
      showDetails.value = true
    } catch (err) {
      console.error('获取订单详情失败', err)
      error.value = '获取订单详情失败'
      orderDetails.value = []
    } finally {
      loading.value = false
    }
  } else {
    showDetails.value = false
  }
}
</script>

<style scoped>
.meal-order-card {
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.meal-order-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
}

.status {
  color: #409eff;
}

.info {
  color: #888;
  font-size: 14px;
  margin: 8px 0;
  display: flex;
  gap: 24px;
}

.footer {
  text-align: right;
  color: #e53935;
  font-size: 16px;
}

.details {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #eee;
}

.item {
  display: flex;
  justify-content: space-between;
  font-size: 15px;
  margin-bottom: 4px;
}

.no-details {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin: 10px 0;
}
</style>
